package com.cafe.pro.service;

import com.cafe.pro.config.CafeConfig;
import com.cafe.pro.dto.DecryptRequest;
import com.cafe.pro.dto.KeyChangeRequest;
import com.cafe.pro.entity.User;
import com.cafe.pro.manager.KeyManager;
import com.cafe.pro.mapper.UserMapper;
import com.cafe.pro.util.CryptoUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.security.PrivateKey;
import java.util.List;

@Service
@Slf4j
@AllArgsConstructor
public class SecurityService {
    private final UserMapper userMapper;
    private final KeyManager keyManager;

    public String decrypt(@RequestBody DecryptRequest request) throws Exception {
        log.info("调用数据解密接口，业务类型：{}，业务数据id：{}，加密数据：{}",
                request.getBusinessType(), request.getBusinessId(), request.getEncryptedData());
        User user = userMapper.selectById(request.getBusinessId());
        if (user == null) {
            log.error("User not found for id: {}", request.getBusinessId());
            return "User not found";
        }
        String aesKey = keyManager.getAesKey(user.getKeyVersion());
        String decryptedData = CryptoUtils.decryptWithAes(request.getEncryptedData(), aesKey);
        log.info("解密成功，解密数据：{}", decryptedData);
        return decryptedData;
    }

    public String changeKey(KeyChangeRequest request) throws Exception {
        List<User> userList = userMapper.selectList(null);
        List<User> updateUserList = userList.stream().filter(user -> user.getKeyVersion().equals(request.getOldVersion())).toList();
        for (User user : updateUserList) {
            String encryptedPhone = user.getEncryptedPhone();
            String encryptedIdCard = user.getEncryptedIdCard();

            // 先使用旧key解密出来原始数据
            String aesKey = keyManager.getAesKey(user.getKeyVersion());
            String phone = CryptoUtils.decryptWithAes(encryptedPhone, aesKey);
            String idCard = CryptoUtils.decryptWithAes(encryptedIdCard, aesKey);

            // 使用新key加密数据
            String newAesKey = keyManager.getAesKey(request.getNewVersion());
            String encryptedPhoneNew = CryptoUtils.encryptWithAes(phone, newAesKey);
            String encryptedIdCardNew = CryptoUtils.encryptWithAes(idCard, newAesKey);

            //更新加密字段以及key的版本号
            user.setEncryptedPhone(encryptedPhoneNew);
            user.setEncryptedIdCard(encryptedIdCardNew);
            user.setKeyVersion(request.getNewVersion());
        }
        userMapper.insertOrUpdate(updateUserList);
        return "OK";
    }
}
